package cz.uvn.orthopedy.server.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import cz.uvn.orthopedy.client.entity.Insurance;

public final class InsuranceJdo {
	
	private InsuranceJdo() {
	}

	public static void editInsurance(Insurance insurance) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Insurance.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			query.setUnique(true);
			Insurance result = (Insurance) query.execute(insurance.getId());
			if (result != null) {
				result.setName(insurance.getName());
				result.setCode(insurance.getCode());
			}
		} finally {
			pm.close();
		}
	}

	public static void createInsurance(Insurance insurance) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(insurance);
		} finally {
			pm.close();
		}
	}
	
	public static void deleteInsurance(Insurance insurance) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Insurance.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			@SuppressWarnings("unchecked")
			List<Insurance> result = (List<Insurance>) query.execute(insurance.getId());
			assert result.size() == 1;
			pm.deletePersistent(result.get(0));
		} finally {
			pm.close();
		}
	}

	public static Insurance[] getInsurances() {
		Insurance[] insurances = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
		try {
			Query q = pm.newQuery(Insurance.class);
			q.setOrdering("name");
			@SuppressWarnings("unchecked")
			List<Insurance> result = (List<Insurance>) q.execute();
			insurances = new Insurance[result.size()];
			for (int i = 0; i < result.size(); i++) {
				Insurance ins = result.get(i);
				insurances[i] = new Insurance(ins.getId(), ins.getName(), ins.getCode());
			}
		} finally {
			pm.close();
		}
		return insurances;
	}

}
